﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using Common.Framework.GlobalEntities.DTO;
using ProductsServer.Core.Entities;
using Common.Framework.GlobalEntities;

namespace ProductsServer.DA
{
    public class DAGenericSearch : BaseDA
    {
        public T Search<T>(GenericSearchData searchData)where T: class, new()
        {
            using(PPEntities dbContext = new PPEntities())
            {
                StringBuilder query = new StringBuilder(string.Format("SELECT * FROM {0} ", searchData.TableName));
                if(searchData.Predicates != null && searchData.Predicates.Count > 0)
                {
                    query.Append("WHERE ");
                    bool flagIndexNotFirst = false;
                    foreach (Predicate pred in searchData.Predicates)
                    {                       
                        if(flagIndexNotFirst)
                        {
                            query.Append("AND ");
                        }
                        flagIndexNotFirst = true;
                        string predType = string.Empty;
                        switch (pred.Type)
                        {
                            case Enums.PredicateType.Like: query.AppendFormat("{0} LIKE '{1}' ", pred.Name, pred.Value); 
                             break;
                            case Enums.PredicateType.BiggerThan: query.AppendFormat("{0} > {1} ", pred.Name, pred.Value); 
                             break;
                            case Enums.PredicateType.SmallerThan: query.AppendFormat("{0} < {1} ", pred.Name, pred.Value); 
                             break;
                            case Enums.PredicateType.Equel: query.AppendFormat("{0} = {1} ", pred.Name, pred.Value);
                             break;
                            case Enums.PredicateType.StartsWith: query.AppendFormat(@"{0} LIKE '{1}%' ", pred.Name, pred.Value);
                             break;
                            default:
                             break;
                        }                        
                    }
                    ProductDTO p1 = dbContext.ExecuteStoreQuery<ProductDTO>(query.ToString()).First();
                    var a = dbContext.ExecuteStoreQuery<T>(query.ToString());
                    T ppp = a.First();
                }
            }
            return new T();
        }

       
    }
    
    
}